package com.szgr.baoyin.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.adapter.MyOrderDetailListAdapter;
import com.szgr.baoyin.model.Address;
import com.szgr.baoyin.model.OrderGoods;
import com.szgr.baoyin.model.OrderMember;
import com.szgr.baoyin.model.Product;
import com.szgr.baoyin.model.RedPacket;
import com.szgr.baoyin.myview.NoScrollListView;
import com.szgr.baoyin.myview.WheelView;
import com.szgr.baoyin.pay.AccessoryProtectPayActivity;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.MyTool;
import com.szgr.baoyin.utils.RLog;
import com.szgr.baoyin.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 订单详情
 */
public class MyOrderDetailActivity extends BaseActivity {
    private List<OrderGoods> data;
    private TextView tv_name;
    private TextView tv_phone;
    private TextView tv_address;
    private Map<String, Object> hashMap;
    private MyOrderDetailListAdapter listAdapter;
    private Map<String, String> addressMap;
    private TextView tv_num;
    private TextView tv_all;
    private String isFromWhere = "1";//来自购物车
    private String type ;
    private OrderMember orderMember;
    private EditText et_dubi;
    private TextView et_hongbao;
    private LinearLayout menuView;
    private WheelView wheelView;
    private Dialog menuDialog;
    private int index = 1;
    private List<RedPacket> packets;
    private RedPacket selectRedPacket;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_my_order_detail);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initActionBar() {
        actionBarTitle.setText("确认订单");
    }

    @Override
    public void initView() {
        packets = new ArrayList<>();
        tv_name = (TextView) findViewById(R.id.my_order_detail_name);
        tv_phone = (TextView) findViewById(R.id.my_order_detail_phone);
        tv_address = (TextView) findViewById(R.id.my_order_detail_address);
        tv_num = (TextView) findViewById(R.id.my_order_detail_num);
        tv_all = (TextView) findViewById(R.id.my_order_detail_all);

        et_dubi = (EditText) findViewById(R.id.order_doubi);
        et_hongbao = (TextView) findViewById(R.id.order_hongbao);
        et_hongbao.setOnClickListener(this);

        initDialog("选择红包");

        Intent intent = getIntent();
        if(intent != null){
            addressMap = new HashMap<>();
            if (intent.hasExtra("address_map")) {
                addressMap = (Map<String, String>) intent.getSerializableExtra("address_map");
                tv_name.setText(addressMap.get("true_name"));
                tv_phone.setText(addressMap.get("mob_phone"));
                tv_address.setText(addressMap.get("area_info") + addressMap.get("address"));
            }
            if (intent.hasExtra("mData")) {
                data = (List<OrderGoods>) intent.getSerializableExtra("mData");
                hashMap = (Map<String, Object>) intent.getSerializableExtra("hashMap");
                //会员信息
                if(hashMap.containsKey("orderMember")) {
                    orderMember = (OrderMember) hashMap.get("orderMember");
                    et_dubi.setHint("(您总共有" + orderMember.getMember_points() + "个都币)");
                }
                int temp = 0;
                for (OrderGoods og : data) {
                    temp += Integer.parseInt(og.getGoods_num());
                }
                tv_num.setText(temp + "");
                double allPrice = 0;
                for (OrderGoods og : data) {
                    double goods_num = Double.parseDouble(og.getGoods_num());
                    double goods_price = Double.parseDouble(og.getGoods_price());
                    allPrice += goods_price * goods_num;
                }
                tv_all.setText(MyTool.formatDouble(allPrice) + "");
            }
            if(intent.hasExtra("isZero")){//0 来自提交订单  1 来自购物车
                isFromWhere = "0";
            }
            if(intent.hasExtra("type")){
                type = intent.getStringExtra("type");
            }
        }

        NoScrollListView nslv_order = (NoScrollListView) findViewById(R.id.my_order_detail_list_view);
        listAdapter = new MyOrderDetailListAdapter(this, data);
        nslv_order.setAdapter(listAdapter);

        findViewById(R.id.my_order_detail_choose_address).setOnClickListener(this);
        findViewById(R.id.my_order_detail_submit).setOnClickListener(this);

        getRedPacket();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.action_bar_left:
                finish();
                break;
            case R.id.my_order_detail_choose_address:
                Intent intent = new Intent(this, AddressActivity.class);
                intent.putExtra("from","order");
                startActivityForResult(intent, 303);
                break;
            case R.id.my_order_detail_submit:
                String offpay_hash = (String) hashMap.get("offpay_hash");
                if(offpay_hash == null){
                    ToastUtils.showToast("地址信息不能为空");
                }

                String member_points;
                if(orderMember != null) {
                    member_points = orderMember.getMember_points();
                }else{
                    member_points = "0";
                }
                String text;
                if(MyTool.isEmpty(et_dubi)){
                    text = "0";
                }else{
                    text = MyTool.getText(et_dubi);
                }
                if(Integer.parseInt(text) > Integer.parseInt(member_points)){
                    ToastUtils.showToast("都币余额不足");
                    return;
                }

                getOrderStep2((String) hashMap.get("vat_hash"), offpay_hash, addressMap.get("address_id"));
                break;
            case R.id.order_hongbao:
                if(packets.size() > 0){
                    List<String> strs = new ArrayList<>();
                    for (RedPacket redPacket: packets) {
                        strs.add(redPacket.getVoucher_title() + ":" + redPacket.getDesc());
                    }
                    wheelView.setItems(strs);
                    wheelView.setSeletion(0);
                    menuDialog.show();
                }
                break;
        }
    }

    private void getRedPacket() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_RED_PACKET,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        RLog.s("--- red --->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject datas = jsonObject.getJSONObject("datas");
                            Object voucher_list1 = datas.get("voucher_list");
                            if(voucher_list1 instanceof JSONObject) {
                                JSONObject voucher_list = datas.getJSONObject("voucher_list");
                                Iterator<String> keys = voucher_list.keys();
                                Gson gson = new Gson();
                                while (keys.hasNext()) {
                                    JSONObject jsonObject1 = voucher_list.getJSONObject(keys.next());
                                    RedPacket redPacket = gson.fromJson(jsonObject1.toString(), RedPacket.class);
                                    packets.add(redPacket);
                                }
                            }else if(voucher_list1 instanceof JSONArray){
                                mHandler.obtainMessage(7878).sendToTarget();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    public void initDialog(String title){
        menuView = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.layout_wheel_view,null);
        View confirm = menuView.findViewById(R.id.confirm);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectRedPacket = packets.get(index - 1);
                et_hongbao.setText(selectRedPacket.getVoucher_title() + selectRedPacket.getVoucher_price() + "元");

                menuDialog.dismiss();
                index = 1;
            }
        });
        View cancel = menuView.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menuDialog.dismiss();
                index = 1;
            }
        });
        TextView tv_title = (TextView) menuView.findViewById(R.id.title);
        tv_title.setText(title);
        wheelView = (WheelView) menuView.findViewById(R.id.wheel_view);

        wheelView.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                index = selectedIndex;
            }
        });
        menuDialog = MyTool.getMenuDialog(this, menuView);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            switch (resultCode) {
                case 304:
                    Address address = (Address) data.getSerializableExtra("address");
                    tv_name.setText(address.getTrue_name());
                    tv_phone.setText(address.getMob_phone());
                    tv_address.setText(address.getArea_info() + address.getAddress());
                    addressMap.put("address_id", address.getAddress_id());
                    changeAddress(address.getArea_id(),address.getCity_id());
                    break;
            }
        }
    }

    /**
     * 切换收货地址
     * @param area_id
     * @param city_id
     */
    private void changeAddress(final String area_id, final String city_id) {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_CHANGE_ADDRESS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("----change address---->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if(jsonObject.has("datas")){
                                JSONObject datas = jsonObject.getJSONObject("datas");
                                String offpay_hash = datas.getString("offpay_hash");
                                hashMap.put("offpay_hash",offpay_hash);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                map.put("freight_hash",(String) hashMap.get("freight_hash"));
                map.put("city_id",city_id);
                map.put("area_id",area_id);
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Constant.REQUEST_SUCCESS:
                    Intent intent = new Intent(MyOrderDetailActivity.this, AccessoryProtectPayActivity.class);
                    intent.putExtra("pay_sn",(String) msg.obj);
                    for (OrderGoods og : data) {
                        if("9".equals(og.getGoods_stcids()[1])){
                            type = Constant.TYPE_01;
                        }
                    }
                    intent.putExtra("type",type);
                    startActivity(intent);
                    finish();
                    break;
                case Constant.REQUEST_FAIL:
                    ToastUtils.showToast("订单提交失败");
                    break;
                case 7878:
                    et_hongbao.setHint("(您还没有红包)");
                    break;
            }
        }
    };

    private void getOrderStep2(final String vat_hash,final String offpay_hash, final String address_id) {
        final StringBuffer sb = new StringBuffer();
        for (int i = 0; i < data.size(); i++) {
            OrderGoods p = data.get(i);
            if (i == data.size() - 1) {
                sb.append(p.getCart_id() + "|" + p.getGoods_num());
            } else {
                sb.append(p.getCart_id() + "|" + p.getGoods_num() + ",");
            }
        }
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_ORDER_SUBMIT,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("---step 2--->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject datas = jsonObject.getJSONObject("datas");
                            if(datas.has("pay_sn")){
                                JSONObject pay_sn = datas.getJSONObject("pay_sn");
                                String pay_sn1 = pay_sn.getString("pay_sn");
                                mHandler.obtainMessage(Constant.REQUEST_SUCCESS,pay_sn1).sendToTarget();
                            }
                        } catch (JSONException e) {
                            mHandler.obtainMessage(Constant.REQUEST_FAIL).sendToTarget();
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("key", MyApplication.getmInstance().getKey());
                map.put("cart_id", sb.toString());
                map.put("ifcart", isFromWhere);
                map.put("address_id", address_id);
                map.put("vat_hash", vat_hash);
                map.put("offpay_hash", offpay_hash);
                map.put("pay_name","online");
                map.put("invoice_id","");

                if(selectRedPacket != null) {
                    map.put("voucher[6]", selectRedPacket.getVoucher_t_id() + "|6|" + selectRedPacket.getVoucher_price());
                }

                String text;
                if(MyTool.isEmpty(et_dubi)){
                    text = "0";
                }else {
                    text = MyTool.getText(et_dubi);
                }
                double money = Double.parseDouble(tv_all.getText().toString().trim());
                if(Integer.parseInt(text) > money){
                    text = ((int)(Math.floor(money))) + "";
                }
                map.put("points[6]",text);
                System.out.println("-----params---->" + map.toString());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }
}
